/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package co.edu.udistrital.util;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import javax.faces.model.SelectItem;
import org.apache.commons.beanutils.BeanUtils;

/**
 *
 * @author Alejo Gamboa B
 */
public class SelectItemUtils {

    private static final Object EMPTY = "empty";

    public static List<SelectItem> buildObjectSelectItems(List<?> elements, String keyProp, String valueProp, boolean needEmptySelectItem) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
        List<SelectItem> selectItems = new ArrayList<SelectItem>();

        if (needEmptySelectItem) {
            selectItems.add(new SelectItem(EMPTY, ""));
        }

        Object key;
        Object value;

        for (Object object : elements) {
            key = BeanUtils.getNestedProperty(object, keyProp);
            value = BeanUtils.getNestedProperty(object, valueProp);
            selectItems.add(new SelectItem(key, value.toString()));
        }

        return selectItems;
    }

}
